package org.loofer.ext.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Debug;
import android.view.InflateException;
import org.loofer.ext.component.logger.Logger;
import java.io.File;
import java.io.FileFilter;

public final class OomUtils {
    private static final long DUMP_FILE_TTL = 259200000;
    private static final String OOM_DIR = "oom";
    private static final String OOM_SUFFIX = ".hprof";
    private static final String TAG = "OomUtils";

    private OomUtils() {
    }

    public static boolean dumpHprofIfNeeded(Context context, Throwable e) {
        if (context == null || e == null || !isOOM(e)) {
            return false;
        }
        try {
            String dir = getOOMDir(context);
            if (dir == null) {
                return false;
            }
            File file = new File(dir + File.separator + (DateUtils.getDate() + "#" + e.getClass().getSimpleName() + OOM_SUFFIX));
            if (isDebuggable(context)) {
                final long now = System.currentTimeMillis();
                FileUtils.delete(file.getParentFile(), new FileFilter() {
                    public boolean accept(File pathname) {
                        return now - pathname.lastModified() > OomUtils.DUMP_FILE_TTL;
                    }
                });
            } else {
                FileUtils.delete(file.getParentFile(), true);
            }
            if (FileUtils.mkdirs(file.getParentFile())) {
                Debug.dumpHprofData(file.getAbsolutePath());
            }
            return true;
        } catch (Throwable t) {
            Logger.w(TAG, "fail to dump hprof", t);
        }
    }

    public static String getHprofDir(Context context) {
        if (context == null) {
            return null;
        }
        return getOOMDir(context);
    }

    public static boolean isOOM(Throwable e) {
        if (e == null) {
            return false;
        }
        if ((e instanceof OutOfMemoryError) || (e instanceof InflateException)) {
            return true;
        }
        return false;
    }

    private static String getOOMDir(Context context) {
        return StorageUtils.getExternalCacheDir(context, OOM_DIR, true);
    }

    private static boolean isDebuggable(Context context) {
        ApplicationInfo appInfo = context.getApplicationInfo();
        return (appInfo == null || (appInfo.flags & 2) == 0) ? false : true;
    }
}
